<template>
	<scroll-view class="scroll" :scroll-y="true" :scroll-into-view="contentPosition" @scroll="scroll"
		:refresher-enabled="!isCompleted" @refresherrefresh="refresherrefresh" :refresher-triggered="triggered">
		<view style="text-align: center;" v-if="isCompleted==false">下拉加载更多</view>
		<view style="text-align: center;" v-if="isCompleted==true">全部加载完成</view>
		<view v-for="(item,index) in list" :key="index" class="item" :id="'message-box'+index">
			<view class="time-lag">
				{{renderMessageDate(item,index)}}
			</view>
			<view class="item_c" :class="{'right':item.from==userId}">
				<!-- 对方头像 -->
				<image :src="item.avatar || 'http://cloud.bxwhl.com/assets/common/img/header.png'" mode="aspectFill"
					v-if="item.from!=userId" class="avatar"></image>
				<!-- 发送失败 -->
				<u-icon name="error-circle-fill" color="#DD001B" size="40" v-if="item.status!='success'"
					@click="sendout(item)"></u-icon>
				<!-- 文本消息 -->
				<view class="border" v-if="item.type=='TIMTextElem'">{{item.payload.text}}</view>
				<!-- 表情消息 -->
				<view class="border_e" v-if="item.type=='TIMFaceElem'">
					<image :src="'../../static/newemoji/'+item.payload.data+'.png'" class="emoji_e"></image>
				</view>
				<!-- 语音消息 -->
				<view class="border_e" v-if="item.type=='TIMSoundElem'" @click="payAudio(item,item.payload.url)">
					<!-- {{item.payload.url}} -->
					<view class="yuandian" v-if="item.from!=userId&&item.isRead==false"></view>
					<u-icon name="volume-up" color="#2979ff" size="50"></u-icon>
				</view>
				<!-- 图片消息 -->
				<image :src="item.payload.imageInfoArray[0].url" mode="" v-if="item.type=='TIMImageElem'"
					class="itemImg" mode="aspectFill" @click="showImageFullScreen(item.payload.imageInfoArray[0].url)">
				</image>
				<!-- cgc消息 -->
				<view class="cgc" v-if="item.type=='TIMCustomElem'&&item.payload.data=='cgc'">
					<image src="../../static/wallet/cgc.png" v-if="JSON.parse(item.payload.description).tradingType==1">
					</image>
					<image src="../../static/wallet/jifen.png"
						v-if="JSON.parse(item.payload.description).tradingType==0"></image>
					<view>
						<view class="cgcnum">{{JSON.parse(item.payload.description).tradingNum}}
							<text v-if="JSON.parse(item.payload.description).tradingType==1">CGC</text>
							<text v-if="JSON.parse(item.payload.description).tradingType==0">积分</text>
						</view>
						<view class="cgcnum">￥{{JSON.parse(item.payload.description).tradingMoney}}</view>
					</view>
					<view class="cgcbtn" @click="cgccon(item.payload.description)">查看详情</view>
				</view>
				<!-- 订单消息 -->
				<view v-if="item.type=='TIMCustomElem'&&item.payload.data=='order'" class="order">
					<view v-if="item.from!=userId">您有一笔市场订单待付款,如已付款请忽略</view>
					<view class="cgc">
						<image src="../../static/wallet/cgc.png"
							v-if="JSON.parse(item.payload.description).tradingType==1"></image>
						<image src="../../static/wallet/jifen.png"
							v-if="JSON.parse(item.payload.description).tradingType==0"></image>
						<view>
							<view class="cgcnum">{{JSON.parse(item.payload.description).tradingNum}}
								<text v-if="JSON.parse(item.payload.description).tradingType==1">CGC</text>
								<text v-if="JSON.parse(item.payload.description).tradingType==0">积分</text>
							</view>
							<view class="cgcnum">￥{{JSON.parse(item.payload.description).tradingMoney}}</view>
						</view>
						<view>
							<view class="cgcbtn" @click="cgccon(item.payload.description)">查看详情</view>
							<view class="cgcbtn" @click="payorder(item.payload.description)" v-if="item.from!=userId">
								立即支付</view>
						</view>
					</view>
				</view>
				<!-- 自己的头像 -->
				<image :src="item.avatar || 'http://cloud.bxwhl.com/assets/common/img/header.png'" mode="aspectFill"
					v-if="item.from==userId" class="avatar"></image>
			</view>
		</view>
		<!-- 底部操作 -->
		<view class="box">
			<view class="box_t">
				<u-icon name="mic" color="#999999" size="60" v-if="ismac==false" @click="ismac=true"></u-icon>
				<u-icon name="edit-pen-fill" color="#999999" size="60" v-if="ismac==true" @click="ismac=false"></u-icon>
				<input type="text" v-model="text" placeholder="输入聊天内容" class="input" v-if="ismac==false" />
				<view v-if="ismac==true" class="mac" @touchstart="mac" @touchend="macstop"
					:class="{'istouch':istouch==true}" @touchmove="touchmove">按住录音 上划取消</view>
				<u-icon name="pause-circle" color="#999999" size="60" @click="eShow=!eShow"></u-icon>
				<!-- #ifndef H5 -->
				<u-icon name="plus-circle" color="#999999" size="60" @click="show=!show"></u-icon>
				<!-- #endif -->
				<view type="default" @click="up()" class="btn">发送</view>
			</view>
			<scroll-view scroll-y="true" class="emojiBox" v-if="eShow">
				<image :src="'../../static/newemoji/'+item+'.png'" v-for="(item,index) in emojiList" class="emoji"
					@click="upIcon(item,index)"></image>
			</scroll-view>
			<view v-if="show" class="box_b">
				<!-- #ifndef H5 -->
				<view @click="upimg">
					<u-icon name="photo" color="#999999" size="60"></u-icon>
					<view>图片</view>
				</view>
				<!-- #endif -->
				<!-- #ifdef MP-WEIXIN -->
				<view @click="upvideo">
					<u-icon name="play-circle" color="#999999" size="60"></u-icon>
					<view>视频</view>
				</view>
				<!-- #endif -->
			</view>
		</view>
		<!-- 视频播放器 -->
		<video :src="video.url" v-if="video.visible" id="videoPlayer" autoplay="true"
			@fullscreenchange="onVideoFullScreenChange" @play="onVideoPlayStart"></video>
	</scroll-view>
</template>
<script>
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	export default {
		components: {},
		data() {
			return {
				fID: "",
				text: "",
				num: "",
				list: [],
				isCompleted: false,
				userId: "",
				contentPosition: "",
				show: false,
				eShow: false,
				emojiList: [],
				video: {
					visible: false,
					url: '',
					context: null
				},
				name: "",
				triggered: false,
				cgcdata: null,
				ismac: false,
				istouch: false, //按住是的背景色
				ly: null,
				fy: null,
				audioShow: true
			};
		},
		// 
		onLoad(e) {
			this.fID = e.id;
			this.name = e.name
			this.userId = uni.getStorageSync('userInfo').userId;
			for (let i = 0; i < 35; i++) {
				this.emojiList.push(i.toString())
			}
			this.onMsg()
			this.getMessageList()
			if (e.cgc) {
				this.cgcdata = e.cgc
				console.log(JSON.parse(this.cgcdata))
				this.upcgc()
			}
			if (e.order) {
				console.log(e.orderid)
				this.uporder(e.order)
			}
		},
		onShow() {
			uni.setNavigationBarTitle({
				title: this.name
			});
		},
		onReady() {
			this.video.context = uni.createVideoContext('videoPlayer');
		},
		onBackPress() {},
		onUnload() {
			let onMessageReceived = function(event) {};
			this.tim.off(this.TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived);
			this.setYd()
		},
		// 监听事件和取消事件监听的入参函数必须为同一个函数！！！！！！
		methods: {
			// 播放语音
			payAudio(item,url) {
				item.isRead=true
				innerAudioContext.src = url;
				innerAudioContext.play();
			},
			// 订单支付
			payorder(item) {
				let data = JSON.parse(item)
				let id = data.tradingRecord.tradingRecordId
				let price = data.tradingMoney
				uni.navigateTo({
					url: '/pages/market/cgcpay?islist=true&id=' + id + "&price=" + price
				})
			},
			// 发送消息
			sendout(message) {
				let promise = this.tim.sendMessage(message);
				promise.then((imResponse) => {
					// 发送成功
					console.log("发送成功", imResponse);
				}).catch(function(imError) {
					// 发送失败
					console.warn('sendMessage error:', imError);
				});
			},
			// 查看cgc详情
			cgccon(item) {
				uni.navigateTo({
					url: "/pages/market/details/details?item=" + item
				})
			},
			//自定义下拉刷新
			refresherrefresh() {
				if (this.triggered) return;
				this.triggered = true;
				this.upList()
				setTimeout(() => {
					this.triggered = false;
				}, 500)
			},
			// 播放视频
			playVideo(e) {
				this.video.visible = true;
				this.video.url = e;
			},
			// 开始播放触发进入全屏
			onVideoPlayStart() {
				this.video.context.requestFullScreen({
					direction: 0
				});
			},
			onVideoFullScreenChange(e) {
				//当退出全屏播放时，隐藏播放器
				if (this.video.visible && !e.detail.fullScreen) {
					this.video.visible = false;
					this.video.context.stop();
				}
			},
			//查看大图
			showImageFullScreen(e) {
				var imagesUrl = [e];
				uni.previewImage({
					urls: imagesUrl
				});
			},
			// 页面滚动隐藏底部
			scroll() {
				this.show = false
				this.eShow = false
			},
			// 接收到的消息处理
			onMessageReceived(e) {
				console.log('接收到消息', e)
				this.list.push(e.data[0])
				this.outBottom()
			},
			// 接收到消息
			onMsg() {
				this.tim.on(this.TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived);
			},
			// 设置时间
			renderMessageDate(message, index) {
				// index=index.toString()
				if (index == 0) {
					return this.formatDate(message.time)
				} else {
					// 此处注意时间戳的位数
					if (message.time - this.list[index - 1].time > 5 * 60) {
						return this.formatDate(message.time)
					}
				}
				return ''
			},
			// 打开某个会话时，第一次拉取消息列表
			getMessageList() {
				let promise = this.tim.getMessageList({
					conversationID: 'C2C' + this.fID,
					count: 15
				});
				promise.then((imResponse) => {
					console.log('页面的会话列表', imResponse)
					this.list = [...imResponse.data.messageList, ...this.list]
					this.outBottom()
					this.num = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
					this.isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
				});
			},
			// 下拉查看更多消息
			upList() {
				let promise = this.tim.getMessageList({
					conversationID: 'C2C' + this.fID,
					nextReqMessageID: this.num,
					count: 15
				});
				promise.then((imResponse) => {
					console.log('下拉页面的会话列表', imResponse)
					this.list = [...imResponse.data.messageList, ...this.list]
					this.num = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
					this.isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
				});
			},
			// 创建语音消息
			mac(e) {
				console.log(e)
				this.fy = e.changedTouches[0].pageY
				this.istouch = true
				uni.showLoading({
					title: '录音中'
				})
				// 录音部分参数
				const recordOptions = {
					duration: 60000, // 录音的时长，单位 ms，最大值 600000（10 分钟）
					sampleRate: 44100, // 采样率
					numberOfChannels: 1, // 录音通道数
					encodeBitRate: 192000, // 编码码率
					format: 'aac' // 音频格式，选择此格式创建的音频消息，可以在即时通信 IM 全平台（Android、iOS、微信小程序和Web）互通
				};
				// 开始录音
				recorderManager.start(recordOptions);
				// 监听录音错误事件
				recorderManager.onError(function(errMsg) {
					console.warn('recorder error:', errMsg);
				});
			},
			touchmove(e) {
				console.log(e)
				this.ly = e.changedTouches[0].pageY
				if ((this.fy - this.ly) > 200) {
					if (this.audioShow == true) {
						this.audioShow = false
						uni.showLoading({
							title: '松开取消发送'
						})
					}
				} else {
					if (this.audioShow == false) {
						this.audioShow = true
						uni.showLoading({
							title: '录音中'
						})
					}
				}
			},
			// TIMSoundElem
			macstop() {
				this.istouch = false
				uni.hideLoading();
				recorderManager.stop()
				console.log(this.audioShow)
				recorderManager.onStop((res) => {
					console.log('recorder stop', res);
					const message = this.tim.createAudioMessage({
						to: this.fID,
						conversationType: this.TIM.TYPES.CONV_C2C,
						payload: {
							file: res
						}
					});
					if(this.audioShow==true){
						console.log(message)
						this.list.push(message)
						this.outBottom()
						this.sendout(message)
					}else{
						this.audioShow=true
					}
				});
			},
			// 发送cgc消息
			upcgc() {
				let message = this.tim.createCustomMessage({
					to: this.fID,
					conversationType: this.TIM.TYPES.CONV_C2C,
					payload: {
						data: 'cgc', // 用于标识该消息是骰子类型消息
						description: this.cgcdata, // 获取骰子点数
						extension: ''
					}
				});
				console.log(message)
				this.list.push(message)
				this.outBottom()
				this.sendout(message)
			},
			// 发送订单信息
			uporder(order) {
				let message = this.tim.createCustomMessage({
					to: this.fID,
					conversationType: this.TIM.TYPES.CONV_C2C,
					payload: {
						data: 'order', // 用于标识该消息是骰子类型消息
						description: order, // 获取骰子点数
						extension: ''
					}
				});
				console.log(message)
				this.list.push(message)
				this.outBottom()
				this.sendout(message)
			},
			// 发送文字消息
			up() {
				if (this.text.trim() != '') {
					// 1. 创建消息实例，接口返回的实例可以上屏
					let message = this.tim.createTextMessage({
						to: this.fID,
						conversationType: this.TIM.TYPES.CONV_C2C,
						payload: {
							text: this.text
						}
					});
					this.list.push(message)
					this.outBottom()
					this.text = ''
					// 2. 发送消息
					this.sendout(message)
				} else {
					this.msg('消息不能为空', "none")
				}
			},
			// 发送表情
			upIcon(item, index) {
				// 1. 创建消息实例，接口返回的实例可以上屏
				let message = this.tim.createFaceMessage({
					to: this.fID,
					conversationType: this.TIM.TYPES.CONV_C2C,
					payload: {
						index: index, // Number 表情索引，用户自定义
						data: item // String 额外数据
					}
				});
				this.list.push(message)
				this.outBottom()
				this.eShow = false
				// 2. 发送消息
				this.sendout(message)
			},
			// 发送视频
			upvideo() {
				uni.chooseVideo({
					sourceType: ['album', 'camera'], // 来源相册或者拍摄
					maxDuration: 60, // 设置最长时间60s
					camera: 'back', // 后置摄像头
					success: (res) => {
						console.log(res)
						// 2. 创建消息实例，接口返回的实例可以上屏
						let message = this.tim.createVideoMessage({
							to: this.fID,
							conversationType: this.TIM.TYPES.CONV_C2C,
							payload: {
								file: res
							},
							onProgress: function(event) {
								console.log('file uploading:', event)
							}
						})
						console.log(message)
						this.list.push(message)
						this.outBottom()
						this.show = false
						// 3. 发送消息
						this.sendout(message)
					}
				})
			},
			upimgH5() {},
			// 发送图片
			upimg() {
				// 1. 选择图片
				uni.chooseImage({
					count: 1, // 只选一张，目前 SDK 不支持一次发送多张图片
					success: (res) => {
						console.log(res)

						// 2. 创建消息实例，接口返回的实例可以上屏
						let message = this.tim.createImageMessage({
							to: this.fID,
							conversationType: this.TIM.TYPES.CONV_C2C,
							payload: {
								file: res
							},
							onProgress: function(event) {
								console.log('file uploading:', event)
							}
						});

						console.log(message)
						this.list.push(message)
						this.outBottom()
						this.show = false
						// 3. 发送图片
						this.sendout(message)
					}
				})
			},
			// 页面滚动到底部
			outBottom() {
				setTimeout(() => {
					this.contentPosition = 'message-box' + (this.list.length - 1);
				}, 100);
			},
			// 消息设置为已读
			setYd() {
				let promise = this.tim.setMessageRead({
					conversationID: 'C2C' + this.fID
				});
				promise.then((imResponse) => {
					console.log('成功:', imResponse);
					// 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
				}).catch(function(imError) {
					// 已读上报失败
					console.log('setMessageRead error:', imError);
				});
			}
		}
	}
</script>
<style>
	.istouch {
		background-color: #E6852C;
	}

	.cgcnum {
		margin-left: 30rpx;
		line-height: 60rpx;
		font-size: 30rpx;
		color: #E6852C;
		margin-right: 30rpx;

	}

	.cgcbtn {
		background-color: #E6852C;
		color: #FFFFFF;
		font-size: 24rpx;
		line-height: 24rpx;
		padding: 10rpx 16rpx;
		border-radius: 10rpx;
		margin: 10rpx;
	}

	page {
		background-color: #F5F5F5;
	}

	.cover-view {
		width: 300rpx;
		height: 300rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.cobox {
		width: 100rpx;
		height: 100rpx;
		background-color: rgba(0, 0, 0, 0.5);
		border-radius: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.video {
		width: 300rpx;
		height: 300rpx;
		margin: 0 20rpx;
		border-radius: 20rpx;
	}

	.itemImg {
		width: 200rpx;
		height: 200rpx;
		margin: 0 20rpx;
		border-radius: 20rpx;
	}

	.emojiBox {
		padding: 20rpx 0 20rpx 20rpx;
		width: 670rpx;
		display: flex;
		flex-wrap: wrap;
		height: 400rpx;
		box-sizing: border-box;
		flex-direction: row;
	}

	.emoji_e {
		width: 60rpx;
		height: 60rpx;
	}

	.emoji {
		width: 60rpx;
		height: 60rpx;
		margin-right: 22.5rpx;
	}

	.border {
		border-radius: 10rpx;
		background-color: #9EEA6A;
		font-size: 28rpx;
		padding: 10rpx;
		margin: 0 20rpx;
		max-width: 550rpx;
		line-height: 48rpx;
	}

	.cgc {
		border-radius: 20rpx;
		background-color: #FFFFFF;
		padding: 20rpx;
		font-size: 28rpx;
		padding: 10rpx;
		margin: 0 20rpx;
		display: flex;
		align-items: center;
	}

	.order {
		border-radius: 20rpx;
		background-color: #FFFFFF;
		padding: 20rpx;
		font-size: 30rpx;
		padding: 10rpx;
		margin: 0 20rpx;
	}

	.cgc>image {
		width: 100rpx;
		height: 100rpx;
	}

	.border_e {
		border-radius: 10rpx;
		background-color: #9EEA6A;
		padding: 10rpx;
		margin: 0 20rpx;
		max-width: 550rpx;
		position: relative;
	}
	.yuandian{
		width: 10rpx;
		height: 10rpx;
		background-color: #FA5151;
		position: absolute;
		right: 4rpx;
	}
	.right {
		justify-content: flex-end;
	}

	.time-lag {
		text-align: center;
		font-size: 26rpx;
	}

	.item {
		margin-top: 40rpx;
		padding: 0 40rpx;
	}

	.item_c {
		display: flex;
		width: 100%;
	}

	.avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 60rpx;
	}

	.btn {
		width: 100rpx;
		height: 60rpx;
		background-color: #F0812D;
		color: #FFFFFF;
		font-size: 26rpx;
		text-align: center;
		line-height: 60rpx;
	}

	.box {
		position: fixed;
		bottom: 0;
		left: 0;

		padding: 20rpx 10rpx;
		justify-content: space-between;
		width: 750rpx;
		background-color: #FFFFFF;
		box-sizing: border-box;
	}

	.box_t {
		display: flex;
		align-items: center;
		background-color: #FFFFFF;
		justify-content: space-between;
	}

	.box_b {
		padding: 40rpx 0;
		background-color: #FFFFFF;
		display: flex;

	}

	.box_b>view {
		width: 100rpx;
		height: 100rpx;
		border: 1rpx #999999 solid;
		border-radius: 10rpx;
		margin: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		font-size: 24rpx;

	}

	.input {
		width: 400rpx;
		height: 60rpx;
		border-radius: 10rpx;
		border: 1px #C8C9CC solid;
		padding-left: 20rpx;
		box-sizing: border-box;
	}

	.mac {
		width: 400rpx;
		height: 60rpx;
		border-radius: 10rpx;
		border: 1px #C8C9CC solid;
		text-align: center;
		line-height: 60rpx;
		font-size: 30rpx;
		color: #999;
	}

	.scroll {
		/* #ifdef H5 */
		height: calc(100vh - 240rpx);
		/* #endif */
		/* #ifndef H5 */
		height: calc(100vh - 150rpx)
			/* #endif */
	}
</style>
